package com.axend.lib_base.utils

import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import androidx.core.content.ContextCompat

class BluetoothScanUtil(private val context: Context) {

    private val bluetoothAdapter: BluetoothAdapter? = getBluetoothAdapter(context)
    private var scanning = false
    private val TAG = "BluetoothScanUtil"

    // BLE 扫描回调
    private var bleScanCallback: BleScanCallback? = null

    // 扫描结果回调接口
    // 扫描结果回调接口
    interface BluetoothScanListener {
        fun onDeviceFound(device: BluetoothDevice, rssi: Int)
        fun onScanFinished()
        fun onError(errorMessage: String)
    }

    // 检查蓝牙是否可用
    fun isBluetoothAvailable(): Boolean {
        return bluetoothAdapter != null && bluetoothAdapter.isEnabled
    }

    private fun getBluetoothAdapter(context: Context): BluetoothAdapter? {
        val bluetoothManager =
            context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        return bluetoothManager.adapter
    }

    // 检查权限
    private fun hasPermissions(): Boolean {
        return getPermissionArray().all { permission ->
            ContextCompat.checkSelfPermission(
                context,
                permission
            ) == PackageManager.PERMISSION_GRANTED
        }
    }

    fun getPermissionArray(): Array<String> {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            arrayOf(
//                Manifest.permission.BLUETOOTH_ADMIN,
//                Manifest.permission.BLUETOOTH,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.BLUETOOTH_CONNECT,
                Manifest.permission.BLUETOOTH_SCAN,
                Manifest.permission.BLUETOOTH_ADVERTISE,
            )
        } else {
            arrayOf(
                Manifest.permission.BLUETOOTH_SCAN,
                Manifest.permission.BLUETOOTH,
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
        }
    }

    // BLE 扫描
    @SuppressLint("MissingPermission")
    fun startBleScan(listener: BluetoothScanListener) {
        bleScanCallback = BleScanCallback(listener)
        bluetoothAdapter?.bluetoothLeScanner?.startScan(bleScanCallback)
    }

    // 停止 BLE 扫描
    @SuppressLint("MissingPermission")
    fun stopBleScan() {
        bleScanCallback?.let {
            bluetoothAdapter?.bluetoothLeScanner?.stopScan(it)
            bleScanCallback = null
        }
    }

    // BLE 扫描回调实现
    @SuppressLint("MissingPermission")
    private class BleScanCallback(private val listener: BluetoothScanListener) : ScanCallback() {
        override fun onScanResult(callbackType: Int, result: ScanResult?) {
            result?.let {
                Log.d("BleScanCallback", "onScanResult: ${it.device.name}")
                listener.onDeviceFound(it.device, it.rssi)
            }
        }

        override fun onBatchScanResults(results: MutableList<ScanResult>?) {

        }

        override fun onScanFailed(errorCode: Int) {
            listener.onError("BLE scan failed with error code: $errorCode")
        }
    }


}